from . import admin
import time
import random
from flask import render_template,request
from app.models import *
import app
from sqlalchemy import or_



@admin.route('/')
def index():

    return render_template('index.html')

@admin.route('/book/list')
def book_list():

    keywords = request.args.get('keywords')

    books = Books.query.filter_by(status=0).order_by(Books.id.desc())
    
    if keywords :
        books = Books.query.filter_by(status=0).filter(or_(
            Books.title.like("%" + keywords + "%"),
            Books.author.like("%" + keywords + "%"))
            ).order_by(Books.id.desc())


    page = request.args.get('page', 1, type=int)    
    pagination = books.paginate(page,per_page=10,error_out=False)
    books = pagination.items
    
    return render_template('booklist.html',books=books,pagination=pagination)


@admin.route('/book/add')
def book_add():
    
    return render_template('bookadd.html')


@admin.route('/book/insert',methods=['POST'])
def book_insert():

    # 接收数据
    data = request.form.to_dict()

    # 检测是否有文件上传
    f = request.files.get('image',None)
    if f:
        data['image'] = uploads(f)
    else:
        # 没有文件上传
        return '<script>alert("请上传图书封面");location.href="/book/add"</script>'


    # 执行数据的添加
    book = Books(**data)
    db.session.add(book)
    db.session.commit()

    # 跳转
    return '<script>alert("录入成功");location.href="/book/list"</script>'


@admin.route('/book/edit',methods=['GET','POST'])
def book_edit():

    bid = request.args.get('bid')

    books = Books.query.get(bid)

    if request.method == 'GET':
        #显示编辑表单
        return render_template('bookedit.html',books=books)

    elif request.method == 'POST':
    
        # 接收数据
        data = request.form.to_dict()

        # 检测是否有文件上传
        f = request.files.get('image',None)
        if f:
            data['image'] = uploads(f)
        else:
            data['image'] = books.image

        data['id']= books.id
        data['status']= books.status
        # 执行数据的修改
        db.session.delete(books)
        book = Books(**data)
        db.session.add(book)
        db.session.commit()

        # 跳转
        return '<script>alert("修改成功");location.href="/book/list"</script>'


@admin.route('/book/block')
def book_block():

    bid = request.args.get('bid')

    books = Books.query.get(bid)

    books.status = 1
    # 执行数据的修改

    db.session.commit()

    # 跳转
    return '<script>alert("下架成功");location.href="/book/list"</script>'

@admin.route('/book/blocklist')
def block_list():

    keywords = request.args.get('keywords')

    books = Books.query.filter_by(status=1).order_by(Books.id.desc())
    
    if keywords :
        books = Books.query.filter_by(status=1).filter(or_(
            Books.title.like("%" + keywords + "%"),
            Books.author.like("%" + keywords + "%"))
            ).order_by(Books.id.desc())


    page = request.args.get('page', 1, type=int)    
    pagination = books.paginate(page,per_page=10,error_out=False)
    books = pagination.items
    
    return render_template('blocklist.html',books=books,pagination=pagination)


@admin.route('/book/open')
def book_open():

    bid = request.args.get('bid')

    books = Books.query.get(bid)

    books.status = 0
    # 执行数据的修改

    db.session.commit()

    # 跳转
    return '<script>alert("还原成功");location.href="/book/list"</script>'


# 封装函数进行文件上传
def  uploads(f):
    
    Suffix = f.filename.split('.').pop()
    filename = str(time.time())+str(random.randint(10000,99999))+'.'+Suffix
    f.save(app.BASE_DIR+'/static/uploads/'+ filename)
    return '/static/uploads/'+ filename